//
//  STCouponAlert.swift
//  iPhone
//
//  Created by Toj on 10/20/22.
//

import UIKit

protocol STCouponAlertDelegate: NSObjectProtocol {
    func couponAlertDidTapClose(_ view: STCouponAlert)
}

class STCouponAlert: UIView {
    
    weak var delegate: STCouponAlertDelegate?
    
    var model: NSObject? { didSet {
       
    } }
    
    func animationCoupon() {
        layoutIfNeeded()
        closeButton.isHidden = true
        backgroundImageView.isHidden = true
        isAnimating = true
        cardImageView.layer.zPosition = cardImageView.frame.width * 0.5
        
        let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
        scaleAnimation.duration = 0.5
        scaleAnimation.fromValue = 0.5
        scaleAnimation.toValue = 1
        scaleAnimation.autoreverses = false
        
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.y")
        rotationAnimation.duration = 0.5
        rotationAnimation.fromValue = -Double.pi*0.5
        rotationAnimation.toValue = 0
        rotationAnimation.delegate = self
        rotationAnimation.autoreverses = false
        
        cardImageView.layer.add(scaleAnimation, forKey: "scale-layer")
        cardImageView.layer.add(rotationAnimation, forKey: "rotate-layer")
    }
    
    private var isAnimating = false
    @objc private func didTapClose() {
        // 让其关闭按钮出现才能点击
        if closeButton.isHidden { return }
        closeButton.isHidden = true
        isAnimating = true
        backgroundView.backgroundColor = .clear
        backgroundImageView.isHidden = true
        let cardView = cardImageView
        let transform = cardView.transform.scaledBy(x: 0.1, y: 0.1)
        UIView.animate(withDuration: 0.5) {
            cardView.transform = transform
        } completion: { finished in
            cardView.isHidden = true
        }
        // 0.4 0.6 0.8
        var iindex = 0.0
        cardImageViews.forEach { view in
            view.isHidden = false
            let delay = 0.1 * iindex + 0.5
            var frame = view.frame
            frame.origin.x = 40
            frame.origin.y = (CGFloat.sr_height - 50)
            frame.size.width = 15
            frame.size.height = 15
            UIView.animate(withDuration: 0.125, delay: delay, options: [.curveEaseIn]) {
                view.frame = frame
            } completion: { finished in
                view.isHidden = true
                view.removeFromSuperview()
            }
            iindex += 1
        }
        let deadline = DispatchTime.now() + 0.5 + Double(cardImageViews.count) * 0.225 // 0.1 + 0.125
        DispatchQueue.main.asyncAfter(deadline: deadline, execute: { [weak self] in
            guard let strongSelf = self else { return }
            self?.delegate?.couponAlertDidTapClose(strongSelf)
            self?.cardImageView.isHidden = true
        })
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupAddSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var layouted = false
    override func layoutSubviews() {
        super.layoutSubviews()
        if layouted { return }
        setupLayoutSubviews()
    }
    
    private lazy var backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.tt_alpha(0.8)
        let tap = UITapGestureRecognizer(target: self, action: #selector(didTapClose))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    private lazy var backgroundImageView: UIImageView = {
        let view = UIImageView()
        view.image = "commodity_coupon_alert_bgimg".to_image
        return view
    }()
    
    private lazy var cardImageView: UIImageView = {
        let view = UIImageView()
        view.image = "commodity_coupon_alert_card".to_image
        return view
    }()
    
    private lazy var cardImageViews: [UIImageView] = {
        var views = [UIImageView]()
        for i in 0..<4 {
            let view = UIImageView()
            view.isHidden = true
            view.image = "commodity_coupon_alert_card_small".to_image
            views.append(view)
        }
        return views
    }()
    
    private lazy var closeButton: UIImageView = {
        let view = UIImageView()
        view.image = "commodity_coupon_alert_close".to_image
        return view
    }()
    
    private lazy var symbolLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont.boldSystemFont(ofSize: 20.f_scale)
        view.text = "₦"
        view.textColor = "#554422".to_color
        return view
    }()
    
    private lazy var priceLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont.boldSystemFont(ofSize: 40.f_scale)
        view.text = "2,400"
        view.textColor = "#554422".to_color
        return view
    }()
    
    private lazy var discountLabel: UILabel = {
        let view = UILabel()
        view.font = UIFont.boldSystemFont(ofSize: 20.f_scale)
        view.text = "OFF"
        view.textColor = "#554422".to_color
        return view
    }()
    
    private lazy var tipsLabel: UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        view.font = UIFont.boldSystemFont(ofSize: 16.f_scale)
        view.text = "CONGRATS ON GETTING A DISCOUNT COUPON"
        view.textColor = "#FFF6A9".to_color
        view.textAlignment = .center
        return view
    }()
    
    private lazy var buttonLabel: UIButton = {
        let view = UIButton()
        view.cm_cornerRadius = 16.ui_scale
        view.isUserInteractionEnabled = false
        view.backgroundColor = "#E8CD8C".to_color
        view.titleLabel?.font = UIFont.systemFont(ofSize: 14.f_scale)
        view.setTitle("USE COUPON NOW", for: .normal)
        view.setTitleColor("#554422".to_color, for: .normal)
        return view
    }()
    
    deinit {
        // print("-->toj: " + #function + " name: STRewardAlertView")
    }
}

extension STCouponAlert {
    
    private func setupAddSubviews() {
        addSubview(backgroundView)
        cardImageViews.forEach { view in
            addSubview(view)
        }
        addSubview(cardImageView)
        addSubview(backgroundImageView)
        addSubview(closeButton)

        cardImageView.addSubview(symbolLabel)
        cardImageView.addSubview(priceLabel)
        cardImageView.addSubview(discountLabel)
        cardImageView.addSubview(tipsLabel)
        cardImageView.addSubview(buttonLabel)
    }
    
    private func setupLayoutSubviews() {
        // print("-->toj: setupLayoutSubviews")
        backgroundView.snp.makeConstraints { make in
            make.edges.equalTo(self)
        }
        
        let cardWidth = 265.ui_scale
        let cardHeight = 315.ui_scale
        let fwidth = frame.width
        let fheight = frame.height
        var x = (fwidth - cardWidth) * 0.5
        var y = (fheight - cardHeight) * 0.5
        cardImageView.frame = CGRect(x: x, y: y, width: cardWidth, height: cardHeight)
        x = (fwidth - 50) * 0.5
        y = (fheight - 50) * 0.5
        cardImageViews.forEach { view in
            view.frame = CGRect(x: x, y: y, width: 50, height: 50)
        }
        
        backgroundImageView.snp.makeConstraints { make in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self.snp.centerY).offset(-30.ui_scale)
            make.width.equalTo(360.ui_scale)
            make.height.equalTo(430.ui_scale)
        }
        
        closeButton.snp.makeConstraints { make in
            make.centerX.equalTo(self)
            make.width.equalTo(24.ui_scale)
            make.height.equalTo(54.ui_scale)
            make.top.equalTo(cardImageView.snp.bottom)
        }
        
        setupLayoutCardViews()
        
        layouted = true
       // cardImageView.transform = cardImageView.transform.scaledBy(x: 0.5, y: 0.5)
    }
    
    private func setupLayoutCardViews() {
        
        priceLabel.snp.makeConstraints { make in
            make.centerX.equalTo(cardImageView)
            make.top.equalTo(70.ui_scale)
        }
        symbolLabel.snp.makeConstraints { make in
            make.bottom.equalTo(priceLabel.snp.bottom).offset(-2)
            make.right.equalTo(priceLabel.snp.left)
        }
        
        discountLabel.snp.makeConstraints { make in
            make.bottom.equalTo(priceLabel.snp.bottom).offset(-2)
            make.left.equalTo(priceLabel.snp.right)
        }
        
        buttonLabel.snp.makeConstraints { make in
            make.bottom.equalTo(cardImageView.snp.bottom).offset(-36.ui_scale)
            make.left.right.equalTo(cardImageView).inset(28.ui_scale)
            make.height.equalTo(32.ui_scale)
        }
        
        tipsLabel.snp.makeConstraints { make in
            make.bottom.equalTo(buttonLabel.snp.top).offset(-20.ui_scale)
            make.left.right.equalTo(buttonLabel)
        }
    }
}


extension STCouponAlert: CAAnimationDelegate {
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        isAnimating = false
        closeButton.isHidden = false
        backgroundImageView.isHidden = false
        closeButton.alpha = 0.1
        backgroundImageView.alpha = 0.1
        cardImageView.layer.zPosition = 0
        UIView.animate(withDuration: 0.2) {
            self.closeButton.alpha = 1
            self.backgroundImageView.alpha = 1
        }
    }
}
